package com.gdc.miaosha.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdc.miaosha.constants.RedisConstant;
import com.gdc.miaosha.entity.MiaoshaOrder;
import com.gdc.miaosha.mapper.MiaoshaOrderMapper;
import com.gdc.miaosha.service.IMiaoshaOrderService;
import com.gdc.miaosha.util.RedisUtil;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;

/**
 * <p>
 * 秒杀订单表 服务实现类
 * </p>
 *
 * @author gdc
 * @since 2022-04-04
 */
@Service
public class MiaoshaOrderServiceImpl extends ServiceImpl<MiaoshaOrderMapper, MiaoshaOrder> implements IMiaoshaOrderService {

    @Override
    public Integer countByUserIdAndGoodsId(@NotNull Integer userId, @NotNull Integer goodsId) {
        // 当查询到Redis中包含秒杀订单时，直接返回数量1（此处的逻辑不合理）
        String miaoShaOrderJson = RedisUtil.getString(RedisConstant.MIAOSHA_ORDER_USER_GOODS + userId + "_" + goodsId);
        if (StrUtil.isNotBlank(miaoShaOrderJson)) {
            return 1;
        }
        return lambdaQuery()
                .eq(MiaoshaOrder::getUserId, userId)
                .eq(MiaoshaOrder::getGoodsId, goodsId)
                .count();
    }

    @Override
    public MiaoshaOrder getByUserIdAndGoodsId(@NotNull Integer userId, @NotNull Integer goodsId) {
        return lambdaQuery()
                .eq(MiaoshaOrder::getUserId, userId)
                .eq(MiaoshaOrder::getGoodsId, goodsId)
                .one();
    }
}
